package com.zz.cogo.filter;

import com.alibaba.fastjson.JSON;
import com.zz.cogo.common.vo.CommonVo;
import com.zz.cogo.common.vo.ResultCode;
import com.zz.cogo.config.FilterProperties;
import com.zz.cogo.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 自定义一个全局过滤器
 *      实现 globalfilter , ordered接口
 */
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties properties;

    @Autowired
    private FilterProperties filterProperties;

    /**
     * 执行过滤器中的业务逻辑
     *     对请求参数中的access-token进行判断
     *      如果存在此参数:代表已经认证成功
     *      如果不存在此参数 : 认证失败.
     *  ServerWebExchange : 相当于请求和响应的上下文(zuul中的RequestContext)
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

//        System.out.println("执行了自定义的全局过滤器");
//        ServerHttpRequest request = exchange.getRequest();
//        String path = request.getURI().getPath();
//        System.out.println(path);
//
//        // 遍历允许访问的路径
//        for (String path_item : this.filterProperties.getAllowPaths()) {
//            // 然后判断是否是符合
//            if(path.startsWith(path_item)){
//                return chain.filter(exchange); //继续向下执行
//            }
//        }
//
//        //1.获取请求参数token
//        String token  = exchange.getRequest().getHeaders().getFirst(properties.getTokeName());
//
//        //2.判断是否存在
//        if(token == null) {
//            //3.如果不存在 : 认证失败
//            return noPower(exchange);
//        }
//        //4.如果存在,验证
//        try {
//            JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
            return chain.filter(exchange); //继续向下执行
//        } catch (Exception e) {
//            e.printStackTrace();
//            return noPower(exchange);
//        }

    }

    /**
     * 指定过滤器的执行顺序 , 返回值越小,执行优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 网关拒绝，返回数据
     *
     * @param
     */
    private Mono<Void> noPower(ServerWebExchange serverWebExchange) {
        // 权限不够拦截
//        serverWebExchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        CommonVo commonVo =new CommonVo(ResultCode.UNAUTH);

        DataBuffer buffer = serverWebExchange.getResponse().bufferFactory()
                .wrap(JSON.toJSONString(commonVo).getBytes(StandardCharsets.UTF_8));
        ServerHttpResponse response = serverWebExchange.getResponse();
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));

    }
}
